﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElCharro01.Models;
using System.IO;
using System.Drawing;
using System.Configuration;
using ElCharro01.Manager;


namespace ElCharro01.Areas.Admin.Controllers
{
    //[Authorize(Roles = "Administrator")]
    public class VariantController : Controller
    {
        private Entities db = new Entities();

        //
        // GET: /Admin/Variant/

        public ViewResult Index()
        {
            return View(db.VariantSet.Include("Product").OrderBy(p => p.Product.Nome).ToList());
        }


        public ViewResult Detail(int id)
        {

            Variant variant = db.VariantSet.Include("Product").Single(v => v.ID == id);
            Product product = db.ProductSet.Single(p => p.ID == variant.Product.ID);

            //fornisco i dati relativi alle disponibilità delle taglie attraverso la viewbag
            ViewBag.Taglia = product.Variant.ToList();

            return View(variant);
        }

        //
        // GET: /Admin/Variant/Create

        public ActionResult Create(int id)
        {
            ViewBag.ProductId = id;
            ViewBag.ProductName = db.ProductSet.Single(p => p.ID == id).Nome;
            return View();
        }


        [HttpPost]
        public ActionResult Create(Variant variant, int ProductId)
        {
            if (ModelState.IsValid)
            {
                variant.Product = db.ProductSet.Single(p => p.ID == ProductId);

                //lavoro sul salvataggio dell'immagine

                //creo un gruppo di immagini 
                ElCharro01.Models.Image Image = new Models.Image();
                ElCharro01.Models.Image ImageBack = new Models.Image();

                if (Request.Files != null)
                {
                    var forntImageUpload = Request.Files["FrontImage"];
                    var backImageUpload = Request.Files["BackImage"];

                    if (forntImageUpload.FileName != "")
                    {
                        var imageName = Path.GetFileName(forntImageUpload.FileName);

                        /* Salvataggio Immagine Temporanea */
                        String tempPath = Server.MapPath("/Content/" + "Images/Tmp/" + imageName);
                        forntImageUpload.SaveAs(tempPath);

                        /* Salvataggio Immagine Originale (nella cartella raw) */
                        String imagePath = Server.MapPath("/Content/" + "Images/Raw/" + imageName);
                        ImageManager.Delete(imagePath);
                        forntImageUpload.SaveAs(imagePath);

                        Bitmap tmp = new Bitmap(tempPath);

                        /* Faccio le dovuto associazioni */
                        Image.Path = imageName;
                        Image.Front = true;

                        /* Cancellazione Immagine Temporanea */
                        tmp.Dispose();
                        ImageManager.Delete(tempPath);
                        db.ImageSet.AddObject(Image);

                    }

                    if (backImageUpload.FileName != "")
                    {
                        var imageName = Path.GetFileName(backImageUpload.FileName);

                        /* Salvataggio Immagine Temporanea */
                        String tempPath = Server.MapPath("/Content/" + "Images/Tmp/" + imageName);
                        backImageUpload.SaveAs(tempPath);

                        /* Salvataggio Immagine Originale (nella cartella raw) */
                        String imagePath = Server.MapPath("/Content/" + "Images/Raw/" + imageName);
                        ImageManager.Delete(imagePath);
                        backImageUpload.SaveAs(imagePath);

                        Bitmap tmp = new Bitmap(tempPath);

                        /* Faccio le dovuto associazioni */
                        ImageBack.Path = imageName;
                        ImageBack.Front = false;

                        /* Cancellazione Immagine Temporanea */
                        tmp.Dispose();
                        ImageManager.Delete(tempPath);
                        db.ImageSet.AddObject(ImageBack);

                    }

                }

                //aggiungo le due immagini al set di immagini della variante
                variant.Image.Add(Image);
                variant.Image.Add(ImageBack);

                // rendo maiuscola la taglia inserita
                variant.Taglia = variant.Taglia.ToUpper();
                //rendo maiuscola la prima lettera del colore
                variant.Colore = UppercaseFirst(variant.Colore);

                db.VariantSet.AddObject(variant);
                db.SaveChanges();

                return RedirectToAction("ShowVariantOfProduct", new { ProductID = ProductId });
            }

            return View(variant);
        }

        //
        // GET: /Admin/Variant/Edit/5

        public ActionResult Edit(int id)
        {
            Variant variant = db.VariantSet.Single(v => v.ID == id);
            return View(variant);
        }

        public ActionResult AddImage(int VariantId)
        {
            ViewBag.ProductName = db.VariantSet.Single(v => v.ID == VariantId).Product.Nome;
            ViewBag.VariantId = VariantId;
            return View();
        }

        [HttpPost]
        public ActionResult AddImageToVariant(int VariantId)
        {
            //istanzio un'immagine
            ElCharro01.Models.Image Image = new Models.Image();
            Variant variant = db.VariantSet.Single(v => v.ID == VariantId);
            if (Request.Files != null)
            {
                var GenericImageUpload = Request.Files["GenericImage"];

                if (GenericImageUpload.FileName != "")
                {
                    var imageName = Path.GetFileName(GenericImageUpload.FileName);

                    /* Salvataggio Immagine Temporanea */
                    String tempPath = Server.MapPath("/Content/" + "Images/Tmp/" + imageName);
                    GenericImageUpload.SaveAs(tempPath);

                    /* Salvataggio Immagine Originale (nella cartella raw) */
                    String imagePath = Server.MapPath("/Content/" + "Images/Raw/" + imageName);
                    ImageManager.Delete(imagePath);
                    GenericImageUpload.SaveAs(imagePath);

                    Bitmap tmp = new Bitmap(tempPath);

                    /* Faccio le dovuto associazioni */
                    Image.Path = imageName;
                    Image.Front = true;

                    /* Cancellazione Immagine Temporanea */
                    tmp.Dispose();
                    ImageManager.Delete(tempPath);
                    db.ImageSet.AddObject(Image);

                }
            }

            //aggiungo le due immagini al set di immagini della variante
            variant.Image.Add(Image);

            db.VariantSet.Attach(variant);
            db.ObjectStateManager.ChangeObjectState(variant, EntityState.Modified);
            db.SaveChanges();

            return RedirectToAction("Edit", new { id = VariantId });
        }

        public ActionResult ImageManagment(int VariantId)
        {
            ViewBag.VariantID = VariantId;
            return View();
        }

        public ActionResult ShowDeleteImage(int VariantId)
        {
            Variant variant = db.VariantSet.Single(v => v.ID == VariantId);
            return View(variant);
        }

        
        public ActionResult DeleteImage(int ImageId, int VariantId)
        {
            Variant variant = db.VariantSet.Single(v => v.ID == VariantId);
            ElCharro01.Models.Image image = db.ImageSet.Single(i => i.ID == ImageId);

            //cancello l'immagine dalla directory Raw
            String imgPath = Server.MapPath("/Content/" + "Images/Raw/" + image.Path);
            Bitmap tmp = new Bitmap(imgPath);
            tmp.Dispose();
            ImageManager.Delete(imgPath);

            //cancello l'entità immagine dal db
            db.ImageSet.DeleteObject(image);
            db.SaveChanges();


            return RedirectToAction("ShowDeleteImage", "Variant", new { VariantId = VariantId });
        }

        [HttpPost]
        public ActionResult Edit(Variant variant)
        {
            if (ModelState.IsValid)
            {
                db.VariantSet.Attach(variant);
                db.ObjectStateManager.ChangeObjectState(variant, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("ShowVariantOfProduct", "Variant", new { ProductID = variant.Product.ID });
            }
            return View(variant);
        }

        //
        // GET: /Admin/Variant/Delete/5

        public ActionResult Delete(int id)
        {
            Variant variant = db.VariantSet.Single(v => v.ID == id);
            return View(variant);
        }

        //
        // POST: /Admin/Variant/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            
            Variant variant = db.VariantSet.Single(v => v.ID == id);
            int productId = variant.Product.ID;

            db.VariantSet.DeleteObject(variant);
            db.SaveChanges();
            return RedirectToAction("ShowVariantOfProduct", "Variant", new { ProductID = productId });
        }

        public ActionResult ShowVariantOfProduct(int ProductID, string Colour = "", string Size = "")
        {
            List<Variant> VariantsList;
            List<string> SizeVariants = new List<String>();
            List<string> ColourVariants = new List<String>();
            ViewBag.ProductID = ProductID;
            ViewBag.ProductName = db.ProductSet.Single(v => v.ID == ProductID).Nome;
            //devo prendere i colori e le taglie disponibili per il prodotto scelto
            VariantsList = db.ProductSet.Single(p => p.ID == ProductID).Variant.ToList();

            foreach (Variant vari in VariantsList)
            {
                SizeVariants.Add(vari.Taglia);
                ColourVariants.Add(vari.Colore);
            }
            ViewBag.SizeVariants = SizeVariants.Distinct();
            ViewBag.ColourVariants = ColourVariants.Distinct();


            //verifico se l'utente ha scelto di visualizzare un determinato colore e/o una determinata taglia
            if (Colour != "" && Size != "")
                return View(db.VariantSet.Include("Product").Where(v => v.Product.ID == ProductID && v.Colore == Colour && v.Taglia == Size));
            else if (Colour == "" && Size != "")
                return View(db.VariantSet.Include("Product").Where(v => v.Product.ID == ProductID && v.Taglia == Size));
            else if (Colour != "" && Size == "")
                return View(db.VariantSet.Include("Product").Where(v => v.Product.ID == ProductID && v.Colore == Colour));
            else
                return View(db.VariantSet.Include("Product").Where(v => v.Product.ID == ProductID).ToList());
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        static string UppercaseFirst(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            char[] a = s.ToCharArray();
            a[0] = char.ToUpper(a[0]);
            return new string(a);
        }
    }


}